import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:my_flutter/webview/flutter_handle.dart';
import 'package:my_flutter/webview/h5_params.dart';
import 'package:webview_flutter/webview_flutter.dart';


late WebViewController _controller;

///自定义的flutter_webview
// ignore: must_be_immutable
class WebViewPage extends StatefulWidget{

  Object? arguments;


   WebViewPage(this.arguments, {Key? key}) : super(key: key);

  @override
  _WebViewPageState createState() => _WebViewPageState();

  //重新加载url
  reloadUrl(String url) {
    debugPrint(url);
    _controller.loadUrl(url);
  }
}

class _WebViewPageState extends State<WebViewPage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;


  String _url = "";
  String _title = "";

  @override
  initState() {
    super.initState();
    _url = (widget.arguments as Map)["url"];
    _title = (widget.arguments as Map)["title"];
    debugPrint("WebViewPage= " + _url + " ");
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(_title),
      ),
      body: Container(
        child: WebView(
          userAgent: 'YMDD',
          initialUrl: _url,
          //JS执行模式 是否允许JS执行
          javascriptMode: JavascriptMode.unrestricted,

          onWebViewCreated: (controller) {
            _controller = controller;
            //可以在初始化时，调用window方法
//            String script = "Toaster.postMessage('哈哈哈哈');";
//            String script = "window.isLogin=是否登录";
//            _controller.evaluateJavascript(script).then((result){
//              print(script + " " + result);
//            }
//            );
          },
          onPageFinished: (url) {
            _controller.evaluateJavascript("document.title").then((result) {
//              setState(() {
//                _title = result;
//              });
            });
          },
          //拦截url
          // navigationDelegate: (NavigationRequest request) {
          //   debugPrint("即将打开 ${request.url}");
          //   if (request.url.startsWith("myapp://")) {
          //     return NavigationDecision.prevent;
          //   }
          //   return NavigationDecision.navigate;
          // },
          //和js交互的通道
          javascriptChannels: <JavascriptChannel>{
            JavascriptChannel(
                name: "callFlutter",
                onMessageReceived: (JavascriptMessage message) {
                  var content = message.message;
                  debugPrint("callFlutter： " + content);
                  //转实体，需要toJson
                  var h5Params = H5Params.fromJson(JsonDecoder().convert(content));
                  //回调js
                  callFlutter(h5Params, (str) {
                    debugPrint("callJs= " + str);
                    String script =
                        "javascript:ISJSBridge.AppCallBack('" + str + "')";
                    _controller.runJavascriptReturningResult(script);
                  });
                })
          },
        ),
      ),
    );
  }
}
